package com.tianji.learning.mq;

import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.po.LikedRecord;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
@RequiredArgsConstructor
public class LikedRecordListener {
    private final IInteractionReplyService replyService;
    /**
     * QA问答系统的点赞记录监听器
     * @param dto
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queue.QA_QUEUE,durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.LIKE_RECORD_EXCHANGE,type= ExchangeTypes.TOPIC),
            key = MqConstants.Key.QA_LIKED_TIMES_KEY
    ))
    public void handleQALikedTimes(List<LikedTimesDTO> dto){
        log.info("收到点赞记录：{}",dto);
        List<InteractionReply> replies = new ArrayList<>(dto.size());
        for (LikedTimesDTO likedTimesDTO : dto) {
            InteractionReply reply = new InteractionReply();
            reply.setId(likedTimesDTO.getBizId());
            reply.setLikedTimes(likedTimesDTO.getLikedTimes());
            replies.add(reply);
        }
        replyService.updateBatchById(replies);
    }

    /**
     * QA问答系统的点赞记录监听器
     * @param map
     */
/*    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queue.QA_RECORD_QUEUE,durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.LIKE_RECORD_EXCHANGE,type= ExchangeTypes.TOPIC),
            key = MqConstants.Key.QA_RECORD_TIMES_KEY
    ))
    public void handleQALikedRecord(Map<Long, Set<String>> map){
        log.info("收到QA点赞的记录：{}",map);
        // bizId -> 点赞的userIdSet
        List<LikedRecord> replies = new ArrayList<>();
        for (Map.Entry<Long, Set<String>> entry : map.entrySet()) {
            Long bizId = entry.getKey();
            Set<String> userIdSet = entry.getValue();
            for (String userId : userIdSet) {
                LikedRecord reply = new LikedRecord();
                reply.setBizId(bizId);
                reply.setBizType("QA");
                reply.setUserId(Long.parseLong(userId));
                replies.add(reply);
            }
        }
        //
    }*/
}
